package com.cxyjy.cfyuiapi.service.impl;

import com.cxyjy.cfyuiapi.service.FFiveTTSService;
import com.cxyjy.common.util.JObjectUtil;
import com.cxyjy.common.util.JResponse;
import com.cxyjy.common.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

import static com.cxyjy.common.util.ResultCode.INPUT_CONTENT_EMPTY;

/**
 * @Author: JrsJony
 * @Date : 2025/1/3 18:14
 */
@Slf4j
@Service
public class FFiveTTSServiceImpl implements FFiveTTSService {
    @Override
    public JResponse submitTTS(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        // 获取表单字段数据
        String refText = httpServletRequest.getParameter("ref_text");
        String genText = httpServletRequest.getParameter("gen_text");
        String model = httpServletRequest.getParameter("model");
        // 打印接收到的表单数据
        log.info("ref_text: " + refText);
        log.info("gen_text: " + genText);
        log.info("model: " + model);
        if(JObjectUtil.isEmpty(genText)){
            return ResultUtil.error(INPUT_CONTENT_EMPTY);
        }
        try {
            // 设置接口的 URL
            URL url = new URL("http://127.0.0.1:5010/api");

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 设置请求头
            String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            // 输出流
            try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
                String lineEnd = "\r\n";
                String twoHyphens = "--";

                // 发送 ref_text 和 gen_text 参数
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"ref_text\"" + lineEnd + lineEnd);
                outputStream.writeBytes("这里填写 1.wav 中对应的文字内容" + lineEnd);

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"gen_text\"" + lineEnd + lineEnd);
                outputStream.writeBytes("这里填写要生成的文本。" + lineEnd);

                // 发送 model 参数，用的是f5-tts
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"model\"" + lineEnd + lineEnd);
                outputStream.writeBytes("f5-tts" + lineEnd);

                // 上传音频文件
                File audioFile = new File("./1.wav");
                byte[] audioBytes = Files.readAllBytes(audioFile.toPath());

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"audio\"; filename=\"1.wav\"" + lineEnd);
                outputStream.writeBytes("Content-Type: audio/wav" + lineEnd + lineEnd);
                outputStream.write(audioBytes);
                outputStream.writeBytes(lineEnd);

                // 结束请求
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // 获取响应
                int responseCode = connection.getResponseCode();
                log.info("响应码: " + responseCode);

                // 读取响应
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = reader.readLine()) != null) {
                        response.append(inputLine);
                    }
                    log.info("响应内容: " + response.toString());
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.justSuccess();
    }
}
